package com.tianma.celue.componet;

import com.tianma.celue.service.IPayService;
import com.tianma.celue.type.PayType;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author lgc
 * @createDate 2020/6/29 - 11:09
 */
@Component
public class PayChooser implements ApplicationContextAware {
   private ApplicationContext applicationContext;
   private  Map<PayType,IPayService> chooseMap = new ConcurrentHashMap<>();
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext=applicationContext;
    }

    //根据key获取具体策略对象
    public IPayService chooseType(PayType p){
        return chooseMap.get(p);
    }

    /**
     * Map封装具体实现策略
     */
    @PostConstruct //beans加载完之后运行该方法
    public void registerPayType(){
        Map<String, IPayService> map = applicationContext.getBeansOfType(IPayService.class);
        map.values().forEach(payService->{
            chooseMap.put(payService.getPayType(),payService);
        });
    }
}
